﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml.Linq;
using System.Xml.Serialization;
using HtmlAgilityPack;

namespace SunwellLauncher
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Variable declarations
        private Realmlists realmlists;
        private FrameworkElement fe;
        private Realmlist rl = null;
        private XDocument doc;
        private HtmlDocument hd;
        private FileSystemWatcher watcher;
        public ObservableCollection<Realmlists> oc;
        public delegate void ListItemsAdd(XDocument doc);
        public static bool closeStoryBoardCompleted = false;
        public string path;
        public string url = "http://sunwell.pl/"; 
        #endregion

        #region Constructors
        public MainWindow()
        {
            InitializeComponent();

            //Thread thread = new Thread(
            //   delegate()
            //   {
                   Dispatcher.Invoke(
                       DispatcherPriority.Normal,
                       new Action(Initialize));
            //   });
            //thread.Start();



            //path = Base.GetPath();
            //hd = new HtmlWeb().Load(url);
        } 
        #endregion

        #region Events
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //fe = (FrameworkElement)this.Template.FindName("MainWin", this);
            //if (null != fe)
            //{
            //    fe.MouseLeftButtonDown += new MouseButtonEventHandler(Window_MouseLeftButtonDown);
            //}

            ////TODO: Run on Thread
            //doc = LoadXML();
            //if (doc != null)
            //{
            //    ListItemsAddFromXML(doc);
            //}
            //else
            //{
            //    CreateWatcher();
            //    CreateXML();
            //    //ListItemsAddFromXML(doc);
            //}

            ////TODO: Multithreading!
            ////GetNews();
            
            //GetNewsFromWebpage();
            //GetRealmStatusFromWebpage();
            
            //SetRealmStatus(1);
            //SetRealmStatus(2);

            ////SendRequest("http://l5k-programming.pl/Sunwell/Licznik/");
            ////SendRequest("http://sunwell.pl/");

            

            ////WriteXML();
            ////ReadXML();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }
        private void MainWin_LocationChanged(object sender, EventArgs e)
        {
            if (rl != null)
            {
                rl.Top = this.Top + ((this.Height - rl.Height) / 2);
                rl.Left = this.Left + ((this.Width - rl.Width) / 2);
            }
        }
        
        private void grdRealm1_MouseEnter(object sender, MouseEventArgs e)
        {
            //grdRealm1.Background = Brushes.AntiqueWhite;
            ImageBrush imgB =
                new ImageBrush(
                    new BitmapImage(new Uri("pack://application:,,,/SunwellLauncher;component/Images/right-top.jpg")));
            imgB.Stretch = Stretch.UniformToFill;
            grdRealm1.Background = imgB;

            

            BitmapImage ico = new BitmapImage();
            ico.BeginInit();
            ico.UriSource = new Uri("pack://application:,,,/SunwellLauncher;component/Images/wotlk.png");
            ico.EndInit();
            imgRealm1.Source = ico;
            imgRealm1.Margin = new Thickness(0);


            lblRealm1Name.Visibility = Visibility.Hidden;
            lblRealm1Type.Visibility = Visibility.Hidden;
            lblRealm1Uptime.Visibility = Visibility.Hidden;
            lblRealm1Players.Visibility = Visibility.Hidden;
            //lblRealm1AllyVsHorde.Content = "12 vs 10";
            lblRealm1AllyVsHorde.Visibility = Visibility.Visible;
            //lblRealm1AvgDiff.Content = "Average diff: 72ms";
            lblRealm1AvgDiff.Visibility = Visibility.Visible;


            imgRealm1Type.VerticalAlignment = VerticalAlignment.Top;
        }
        private void grdRealm1_MouseLeave(object sender, MouseEventArgs e)
        {
            //grdRealm1.Background = Brushes.Gray;
            ImageBrush imgB =
                new ImageBrush(
                    new BitmapImage(new Uri("pack://application:,,,/SunwellLauncher;component/Images/right-bg.jpg")));
            imgB.Stretch = Stretch.None;
            grdRealm1.Background = imgB;



            BitmapImage ico = new BitmapImage();
            ico.BeginInit();
            ico.UriSource = new Uri("pack://application:,,,/SunwellLauncher;component/Images/status_up.png");
            ico.EndInit();
            imgRealm1.Source = ico;
            imgRealm1.Margin = new Thickness(5);

            lblRealm1Name.Visibility = Visibility.Visible;
            lblRealm1Type.Visibility = Visibility.Visible;
            lblRealm1Uptime.Visibility = Visibility.Visible;
            lblRealm1Players.Visibility = Visibility.Visible;
            //lblRealm1AllyVsHorde.Content = "12 vs 10";
            lblRealm1AllyVsHorde.Visibility = Visibility.Hidden;
            //lblRealm1AvgDiff.Content = "Average diff: 50ms";
            lblRealm1AvgDiff.Visibility = Visibility.Hidden;

            //InlineCollection ilc = txtbRealm1AllyVsHorde.Inlines;
            //ilc.Clear();



            imgRealm1Type.VerticalAlignment = VerticalAlignment.Bottom;
        }
        private void grdRealm2_MouseEnter(object sender, MouseEventArgs e)
        {
            //grdRealm1.Background = Brushes.AntiqueWhite;
            ImageBrush imgB =
                new ImageBrush(
                    new BitmapImage(new Uri("pack://application:,,,/SunwellLauncher;component/Images/right-top.jpg")));
            imgB.Stretch = Stretch.UniformToFill;
            grdRealm2.Background = imgB;

            BitmapImage ico = new BitmapImage();
            ico.BeginInit();
            ico.UriSource = new Uri("pack://application:,,,/SunwellLauncher;component/Images/wotlk.png");
            ico.EndInit();
            imgRealm2.Source = ico;
            imgRealm2.Margin = new Thickness(0);


            lblRealm2Name.Visibility = Visibility.Hidden;
            lblRealm2Type.Visibility = Visibility.Hidden;
            lblRealm2Uptime.Visibility = Visibility.Hidden;
            lblRealm2Players.Visibility = Visibility.Hidden;
            //lblRealm2AllyVsHorde.Content = "12 vs 10";
            lblRealm2AllyVsHorde.Visibility = Visibility.Visible;
            //lblRealm2AvgDiff.Content = "Average diff: 50ms";
            lblRealm2AvgDiff.Visibility = Visibility.Visible;

            
            //Run ally = new Run();
            //ally.Text = "12";
            //ally.Foreground = new SolidColorBrush(Color.FromRgb(70, 71, 220)); //Brushes.Blue;
            //ally.FontSize = 28;
            //Run horde = new Run();
            //horde.Text = "10";
            //horde.Foreground = new SolidColorBrush(Color.FromRgb(231, 44, 44)); //Brushes.DarkRed;
            //horde.FontSize = 28;

            //InlineCollection ilc = txtbRealm2AllyVsHorde.Inlines;
            //ilc.Add(ally);
            //ilc.Add(" vs ");
            //ilc.Add(horde);
            //ally = null;
            //horde = null;



            imgRealm2Type.VerticalAlignment = VerticalAlignment.Top;
        }
        private void grdRealm2_MouseLeave(object sender, MouseEventArgs e)
        {
            //grdRealm2.Background = Brushes.Gray;
            ImageBrush imgB =
                new ImageBrush(
                    new BitmapImage(new Uri("pack://application:,,,/SunwellLauncher;component/Images/right-bg.jpg")));
            imgB.Stretch = Stretch.None;
            grdRealm2.Background = imgB;

            BitmapImage ico = new BitmapImage();
            ico.BeginInit();
            ico.UriSource = new Uri("pack://application:,,,/SunwellLauncher;component/Images/status_up.png");
            ico.EndInit();
            imgRealm2.Source = ico;
            imgRealm2.Margin = new Thickness(5);

            lblRealm2Name.Visibility = Visibility.Visible;
            lblRealm2Type.Visibility = Visibility.Visible;
            lblRealm2Uptime.Visibility = Visibility.Visible;
            lblRealm2Players.Visibility = Visibility.Visible;
            //lblRealm2AllyVsHorde.Content = "12 vs 10";
            lblRealm2AllyVsHorde.Visibility = Visibility.Hidden;
            //lblRealm2AvgDiff.Content = "Average diff: 50ms";
            lblRealm2AvgDiff.Visibility = Visibility.Hidden;

            //InlineCollection ilc = txtbRealm2AllyVsHorde.Inlines;
            //ilc.Clear();



            imgRealm2Type.VerticalAlignment = VerticalAlignment.Bottom;
        }

        private void btnMinimalize_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            //string path = Directory.GetCurrentDirectory();
            string filePath = path + "/Wow.exe";

            if (File.Exists(filePath))
            {
                Process.Start(filePath);
            }
            else
            {
                //TODO: Show custom message box

                MessageBox.Show("Nie znaleziono pliku WoW.exe! \n\nSunwell launcher nie znajduje się w głównym katalogu gry World of Warcraft. \nBy naprawić ten problem umieść Sunwell launcher w głównym katalogu gry.", "Uwaga!", MessageBoxButton.OK, MessageBoxImage.Warning);  
            }
        }
        private void btnRealmlist_Click(object sender, RoutedEventArgs e)
        {
            if (brdRealmlistBorder.Width == 0) //(grdRealmlist.Width == 0)
            {
                //grdRealmlist.Width = 160;
                Grid.SetColumnSpan(grdContent, 1);
                Grid.SetColumnSpan(brdContentBorder, 1);
                brdRealmlistBorder.Width = 160;
                MainWin.Width = 750;
                
            }
            else
            {
                //grdRealmlist.Width = 0;
                Grid.SetColumnSpan(grdContent, 2);
                Grid.SetColumnSpan(brdContentBorder, 2);
                brdRealmlistBorder.Width = 0;
                
                MainWin.Width = 575;
            }
        }
        
        private void btnSet_Click(object sender, RoutedEventArgs e)
        {
            string langV = string.Empty;
            string realmlist = string.Empty;
            string address = string.Empty;
            //string path = Directory.GetCurrentDirectory();
            langV = (Directory.Exists(path + "/Data/enGB"))
                        ? "enGB" : Directory.Exists(path + "/Data/enUS") ? "enUS" : string.Empty;

            //TODO: Check current realmlist.wtf file and compare with XML (Skip all whitespaces and compare)

            var selRealm = (Realm)lstbRealmlist.SelectedItem;

            switch (langV)
            {
                case "enGB":
                    address = selRealm.Address;
                    realmlist = "set realmlist " + address;
                    File.WriteAllText(path + "/Data/enGB/realmlist.wtf", realmlist);
                    break;
                case "enUS":
                    address = selRealm.Address;
                    realmlist = "set realmlist " + address;
                    File.WriteAllText(path + "/Data/enUS/realmlist.wtf", realmlist);
                    break;
                default:
                    //TODO: MessageBox: "Unknown language version"

                    MessageBox.Show("Nie rozpoznano wersji językowej gry!\n\nSunwell launcher obsługuje wersje enGB i enUS.\n\n//Upewnij się również, że Sunwell Launcher znajduje sie w głównym katalogu gry.", "Uwaga!", MessageBoxButton.OK, MessageBoxImage.Warning);  
                    break;
            }
        }
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            //AddWindow addW = new AddWindow() { Owner = this };
            //addW.ShowDialog();

            new AddWindow(realmlists, doc) {Owner = this}.ShowDialog();
        }
        private void btnDel_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Czy na pewno usunąć wybraną pozycję?", "Uwaga!",
                MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                Realm toDel = (Realm)lstbRealmlist.SelectedItem;
                realmlists.Realm.Remove(toDel);
                XElement xElement = doc.Element("Realmlists");
                if (xElement != null)
                    xElement.Elements("Realm").FirstOrDefault(x =>
                        x.Element("name").Value == toDel.Name &&
                        x.Element("address").Value == toDel.Address &&
                        x.Element("website").Value == toDel.Website).Remove();
                doc.Save(path + "/Realmlists.xml");
            }
        }
        
        //Fading in/out on app Open/Close
        private void MainWin_Closing(object sender, CancelEventArgs e)
        {
            if (!closeStoryBoardCompleted)
            {
                //Storyboard closeStoryBoard = FindResource("closeStoryBoard") as Storyboard;
                closeStoryBoard.Begin();
                e.Cancel = true;
            }
        }
        private void closeStoryBoard_Completed(object sender, EventArgs e)
        {
            closeStoryBoardCompleted = true;
            this.Close();
            if (rl != null) { rl.Close(); }
            Application.Current.Shutdown();
        }
        #endregion

        #region Methods

        public void Initialize()
        {
            fe = (FrameworkElement)Template.FindName("MainWin", this);
            hd = new HtmlWeb().Load(url);
            path = Base.GetPath();
            doc = LoadXML();

            if (fe != null)
                fe.MouseLeftButtonDown += new MouseButtonEventHandler(Window_MouseLeftButtonDown);
            
            if (doc != null)
                ListItemsAddFromXML(doc);

            else
            {
                CreateWatcher();
                CreateXML();
                //ListItemsAddFromXML(doc);
            }
            
            GetNewsFromWebpage();
            GetRealmStatusFromWebpage();
        }

        public XDocument LoadXML()
        {
            //string path = Base.GetPath(); //Directory.GetCurrentDirectory();
            XDocument xDocument = File.Exists(path + @"\Realmlists.xml") ? XDocument.Load(path + @"\Realmlists.xml") : null;

            return xDocument;
        }
        private void CreateXML()
        {
            //List<string> list = new List<string>() {"pierwszy", "drugi" };

            XDocument doc =
              new XDocument(
                new XElement("Realmlists",
                  new XElement("Realm", new XElement("name", "Sunwell"), new XElement("address", "176.9.132.194"), new XElement("website", "http://sunwell.pl/"))
                //,list.Select(x => new XElement("data", new XAttribute("value", x)))
                            )
                           );

            //string path = Directory.GetCurrentDirectory();
            doc.Save(path + "/Realmlists.xml");
        }

        public void ListItemsAddFromXML(XDocument doc)
        {
            XmlSerializer reader = new XmlSerializer(typeof(Realmlists));
            realmlists = (Realmlists)reader.Deserialize(doc.CreateReader());
            lstbRealmlist.DataContext = realmlists.Realm;
        }

        private string GetSunwellRealmlist()
        {
            return "176.9.132.194";
        }
        
        private void SendRequest(string url)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.GetResponse();
            //HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            //Stream s = webResponse.GetResponseStream();
            //StreamReader reader;
            //reader = new StreamReader(s);
            //string str = reader.ReadToEnd();

            //<WebBrowser x:Name="wbViews" Grid.Column="1" Margin="100,0,0,0" Width="100"></WebBrowser>
            //var wb = new WebBrowser();
            //wbViews.NavigateToString(str);
            //wb.NavigateToStream(s);
        }

        private void GetNewsFromWebpage()
        {
            if (hd != null)
            {
                var newsDiv = hd.DocumentNode.Descendants()
                                .Where(n => n.Name == "div" && n.Attributes.Contains("class") && n.Attributes["class"].Value.Contains("news-container"))
                                .FirstOrDefault();

                var image = url + newsDiv.Descendants("img").Select(x => x.Attributes["src"].Value).SingleOrDefault();

                var title =
                    newsDiv.Elements("span").Where(x => x.Attributes["class"].Value.Contains("news-title")).
                        SingleOrDefault();

                var author =
                    newsDiv.Elements("span").Where(x => x.Attributes["class"].Value.Contains("news-author")).
                        SingleOrDefault();

                newsDiv.RemoveChild(title);
                newsDiv.RemoveChild(author);

                var content = newsDiv.InnerText.Replace("&nbsp;", string.Empty).Trim();


                imgNewsImg.Source = GetImgFromUrl(image);
                lblNewsTitle.Content = title.InnerText;
                lblNewsCreatedBy.Content = author.InnerText;
                txtbNewsContent.Text = content;
            }
            


            //var document = new HtmlWeb().Load(url);
            //var urls = document.DocumentNode.Descendants("img")
            //                                .Select(e => e.GetAttributeValue("src", null))
            //                                .Where(s => !String.IsNullOrEmpty(s));

            #region Old_2DEL
            //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            //HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            //var encoding = webResponse.ContentEncoding;
            //Stream stream = webResponse.GetResponseStream();
            //StreamReader reader = new StreamReader(stream); //(stream, System.Text.Encoding.GetEncoding("utf-8"));
            //var xs = reader.ReadToEnd();

            //WebClient n = new WebClient();
            //string web = n.DownloadString(url);

            //HtmlDocument htmlDoc = new HtmlDocument();
            //htmlDoc.DetectEncoding(reader);
            //htmlDoc.OptionFixNestedTags = true;
            //htmlDoc.Load(reader);
            //string tst = htmlDoc.DocumentNode.ToString();

            //if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
            //{
            //    // Handle any parse errors as required
            //}
            //else
            //{
            //    if (htmlDoc.DocumentNode != null)
            //    {
            //        //var body = from html in htmlDoc.DocumentNode.Element("body").InnerText select html;

            //        //var ht = htmlDoc.DocumentNode.Element("html").ChildNodes;
            //        var html = htmlDoc.DocumentNode.Descendants("body").Select(x => x.ChildNodes).SingleOrDefault();
            //        var bd = htmlDoc.DocumentNode.Descendants("body").Select(x => x.ChildNodes);
            //        var wrapper = htmlDoc.DocumentNode.Descendants("div").Select(x => x.ChildNodes);

            //        var divs = htmlDoc.DocumentNode.Descendants("div");

            //        var dataa =
            //              from div in htmlDoc.DocumentNode.Descendants("div")
            //              from span in div.Descendants("span").Where(x => x.Attributes["class"].Value == "news-title")
            //              select div;


            //        HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");

            //        if (bodyNode != null)
            //        {
            //            // Do something with bodyNode

            //            //news-container
            //            var data =
            //              from div in htmlDoc.DocumentNode.Descendants("div")
            //              from span in div.Descendants("span").Where(x => x.Attributes["class"].Value == "news-title")
            //              select div;

            //            //var data =
            //            //  from tr in htmlDoc.DocumentNode.Descendants("tr")
            //            //  from td in tr.Descendants("td").Where(x => x.Attributes["class"].Value == "name")
            //            //  where td.InnerText.Trim() == "Test1"
            //            //  select tr;
            //        }
            //    }
            //}

            //stream.Close(); 
            #endregion
        }
        private void GetRealmStatusFromWebpage()
        {
            // 30s <- status refreshing time
            // <div id="realmstatuscode"> => <div class="realm-border" onmouseover="tooltip.show(...

            if (hd != null)
            {
                var statsDiv =
                    hd.DocumentNode.Descendants().Where(
                        s =>
                        s.Name == "div" && s.Attributes.Contains("id") &&
                        s.Attributes["id"].Value.Contains("realmstatuscode")).FirstOrDefault();

                var realms =
                    statsDiv.Descendants().Where(
                        r =>
                        r.Name == "div" && r.Attributes.Contains("class") &&
                        r.Attributes["class"].Value.Contains("realm-border") && r.Attributes.Contains("onmouseover"));

                #region Realm #1 Get
                var realm1name =
                            realms.FirstOrDefault().Elements("div").Where(
                                s => s.Attributes["class"].Value.Contains("realm-name")).FirstOrDefault().InnerText;
                var realm1status = realms.FirstOrDefault().Element("img").Attributes["src"].Value;
                var realm1upTime = realms.FirstOrDefault().Elements("div").Where(
                        s => s.Attributes["class"].Value.Contains("realm-text")).FirstOrDefault().InnerText;
                var realm1stats = realms.FirstOrDefault().Attributes["onmouseover"].Value;

                var stats1 = GetValuesFromServerStats(realm1stats);
                RealmStatus r1 = new RealmStatus()
                                     {
                                         name = realm1name,
                                         uptime = realm1upTime,
                                         //players = ,
                                         //playersMax = ,
                                         avgDiff = stats1["AvgDiff"],
                                         type = stats1["RealmType"],
                                         alliance = stats1["Ally"],
                                         horde = stats1["Horde"],
                                         //Rev = ,
                                         Image = GetImgFromUrl(url + realm1status)
                                     }; 
                #endregion

                #region Realm #2 Get
                var realm2name =
                            realms.LastOrDefault().Elements("div").Where(
                                s => s.Attributes["class"].Value.Contains("realm-name")).FirstOrDefault().InnerText;
                var realm2status = realms.LastOrDefault().Element("img").Attributes["src"].Value;
                var realm2upTime = realms.LastOrDefault().Elements("div").Where(
                        s => s.Attributes["class"].Value.Contains("realm-text")).FirstOrDefault().InnerText;
                var realm2stats = realms.LastOrDefault().Attributes["onmouseover"].Value;

                var stats2 = GetValuesFromServerStats(realm2stats);
                RealmStatus r2 = new RealmStatus()
                {
                    name = realm2name,
                    uptime = realm2upTime,
                    //players = ,
                    //playersMax = ,
                    avgDiff = stats2["AvgDiff"],
                    type = stats2["RealmType"],
                    alliance = stats2["Ally"],
                    horde = stats2["Horde"],
                    //Rev = ,
                    Image = GetImgFromUrl(url + realm2status)
                }; 
                #endregion

                #region Realm #1 Set
                lblRealm1Name.Content = r1.name;
                lblRealm1Type.Content = r1.type;
                lblRealm1Uptime.Content = r1.uptime.Substring(0, r1.uptime.IndexOf(" &")); //"Up: " + r1.uptime;
                lblRealm1Players.Content = r1.uptime.Substring(r1.uptime.IndexOf("&nbsp; ") + 7, r1.uptime.Length - r1.uptime.IndexOf("&nbsp; ") - 7); //"Players: " + r1.players + " (max " + r1.playersMax + ")";
                lblRealm1AvgDiff.Content = "Average diff: " + r1.avgDiff + "ms";
                imgRealm1.Source = r1.Image;

                Run ally1 = new Run()
                {
                    Text = r1.alliance,
                    Foreground = new SolidColorBrush(Color.FromRgb(70, 71, 220)),
                    FontSize = 28
                };
                Run horde1 = new Run()
                {
                    Text = r1.horde,
                    Foreground = new SolidColorBrush(Color.FromRgb(231, 44, 44)),
                    FontSize = 28
                };

                InlineCollection ilc1 = txtbRealm1AllyVsHorde.Inlines;
                ilc1.Add(ally1);
                ilc1.Add(" vs ");
                ilc1.Add(horde1); 
                #endregion

                #region Realm #1 Set
                lblRealm2Name.Content = r2.name;
                lblRealm2Type.Content = r2.type;
                lblRealm2Uptime.Content = r2.uptime.Substring(0, r2.uptime.IndexOf(" &")); //"Up: " + r2.uptime;
                lblRealm2Players.Content = r2.uptime.Substring(r2.uptime.IndexOf("&nbsp; ") + 7, r2.uptime.Length - r2.uptime.IndexOf("&nbsp; ") - 7); //"Players: " + r2.players + " (max " + r2.playersMax + ")";
                lblRealm2AvgDiff.Content = "Average diff: " + r2.avgDiff + "ms";
                imgRealm2.Source = r2.Image;

                Run ally2 = new Run()
                {
                    Text = r2.alliance,
                    Foreground = new SolidColorBrush(Color.FromRgb(70, 71, 220)),
                    FontSize = 28
                };
                Run horde2 = new Run()
                {
                    Text = r2.horde,
                    Foreground = new SolidColorBrush(Color.FromRgb(231, 44, 44)),
                    FontSize = 28
                };

                InlineCollection ilc2 = txtbRealm2AllyVsHorde.Inlines;
                ilc2.Add(ally2);
                ilc2.Add(" vs ");
                ilc2.Add(horde2);
                #endregion
            }
        }

        
        private Dictionary<string, string> GetValuesFromServerStats(string realm)
        {
            var dict = GetDictionaryFromRealmStats(realm);
            var dct = new Dictionary<string, string>();

            foreach (var d in dict)
            {
                var val = (d.Value.IndexOf(": ") >= 0) ? d.Value.Substring(d.Value.IndexOf(": ")+2, d.Value.Length - d.Value.IndexOf(": ")-2) : string.Empty;

                switch (d.Key)
                {
                    case 0: dct.Add("RealmType", val);
                        break;
                    case 1: dct.Add("Ally", d.Value.Substring(0, d.Value.IndexOf(" vs ")));
                            dct.Add("Horde", d.Value.Substring(d.Value.IndexOf(" vs ")+4, d.Value.Length-d.Value.IndexOf(" vs ")-4));
                        break;
                    case 2: dct.Add("AvgDiff", val);
                        break;
                    case 3: dct.Add("Rev", val);
                        break;
                    //case 4: dct.Add("???", string.Empty);
                    //    break;
                    case 5: dct.Add("Wintergrasp", d.Value.Substring(d.Value.IndexOf("za ") + 3, d.Value.Length - d.Value.IndexOf("za ") - 3));
                        break;
                    case 6: dct.Add("ExpKillRate", val);
                        break;
                    case 7: dct.Add("ExpQuestRate", val);
                        break;
                    case 8: dct.Add("ExpExplorationRate", val);
                        break;
                    case 9: dct.Add("DropRate", val);
                        break;
                    case 10: dct.Add("GoldRate", val);
                        break;
                    case 11: dct.Add("ReputationRate", val);
                        break;
                    case 12: dct.Add("HonorRate", val);
                        break;
                    case 13: dct.Add("ProfessionRate", val);
                        break;
                }
            }

            return dct;
        }
        private Dictionary<int, string> GetDictionaryFromRealmStats(string realm)
        {
            var dict = new Dictionary<int, string>();
            int i = 0;

            //var rows = GetSubstringByString("tooltip.show('", "');", realm).Split(new[] { "<BR>" }, StringSplitOptions.RemoveEmptyEntries);
            var rows = GetSubstringByString("tooltip.show('", "'", realm).Split(new[] { "<BR>" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var s in rows)
            {
                var tmp = "<div>" + s + "</div>";
                var hn = HtmlNode.CreateNode(tmp);
                var tt = hn.InnerText;

                dict[i] = tt;
                i++;
            }

            return dict;
        }
        

        private string GetSubstringByString(string a, string b, string c)
        {
            return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b, a.Length) - c.IndexOf(a) - a.Length));
        }

        private void GetNews()
        {
            //TODO: Change doc path to Sunwell XML file
            XDocument doc = XDocument.Load("http://l5k-programming.pl/Sunwell/News.xml");
            var image = doc.Descendants("image").Select(x => x.Value).SingleOrDefault();
            var title = doc.Descendants("title").Select(x => x.Value).SingleOrDefault(); //doc.Element("title").Value;
            var createdBy = doc.Descendants("createdBy").Select(x => x.Value).SingleOrDefault();
            var date = doc.Descendants("date").Select(x => x.Value).SingleOrDefault();
            var content = doc.Descendants("content").Select(x => x.Value).SingleOrDefault();

            imgNewsImg.Source = GetImgFromUrl(image);
            lblNewsTitle.Content = title;
            lblNewsCreatedBy.Content = "przez " + createdBy + ", " + date + ".";
            txtbNewsContent.Text = content;

            //Run ln = new Run("http://stackoverflow.com/");
            //Hyperlink hl = new Hyperlink(ln);//{Name = "asd", NavigateUri = new Uri("http://stackoverflow.com/")};
            //txtbNewsContent.Text = "Serdecznie gratulujemy pierwszym zdobywcom achievementa [What A Long, Strange Trip It's Been] i jednocześnie posiadaczom [Reins of the Violet Proto-Drake]. W tej chwili wszystkie doroczne eventy są naprawione. Nie tylko działają achievementy, ale też eventy były naprawiane z dużą starannością i dbałością o szczegóły. Życzymy powodzenia innym starającym się o ten achievement i mounta :)";
          //txtbNewsContent.Inlines.Add(hl);
            //txtbNewsContent.Text = "Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas 1";
            //txtbNewsContent.Text = "Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas das dassdsadas Conntent sda as das dasda sdasdsadasd asdas1";
        }
        private void SetRealmStatus(int realmID)
        {
            //TODO: Separe main realm info from realm details and make refreshing for data
            var rs = GetRealmStatus(realmID);
            
            switch (realmID)
            {
                case 1:
                    lblRealm1Name.Content = rs.name;
                    lblRealm1Uptime.Content = "Up: " + rs.uptime;
                    lblRealm1Players.Content = "Players: " + rs.players + " (max " + rs.playersMax + ")";
                    //TODO: realm type
                    //lblRealm1AllyVsHorde = 
                    lblRealm1AvgDiff.Content = "Average diff: " + rs.avgDiff + "ms";

                    Run ally1 = new Run()
                                   {
                                       Text = rs.alliance,
                                       Foreground = new SolidColorBrush(Color.FromRgb(70, 71, 220)),
                                       FontSize = 28
                                   };
                    Run horde1 = new Run()
                                    {
                                        Text = rs.horde,
                                        Foreground = new SolidColorBrush(Color.FromRgb(231, 44, 44)),
                                        FontSize = 28
                                    };

                    InlineCollection ilc1 = txtbRealm1AllyVsHorde.Inlines;
                    ilc1.Add(ally1);
                    ilc1.Add(" vs ");
                    ilc1.Add(horde1);
                    break;
                case 2:
                    lblRealm2Name.Content = rs.name;
                    lblRealm2Uptime.Content = "Up: " + rs.uptime;
                    lblRealm2Players.Content = "Players: " + rs.players + " (max " + rs.playersMax + ")";
                    //TODO: realm type
                    //lblRealm2AllyVsHorde = 
                    lblRealm2AvgDiff.Content = "Average diff: " + rs.avgDiff + "ms";

                    Run ally2 = new Run()
                                   {
                                       Text = rs.alliance,
                                       Foreground = new SolidColorBrush(Color.FromRgb(70, 71, 220)),
                                       FontSize = 28
                                   };
                    Run horde2 = new Run()
                                    {
                                        Text = rs.horde,
                                        Foreground = new SolidColorBrush(Color.FromRgb(231, 44, 44)),
                                        FontSize = 28
                                    };

                    InlineCollection ilc2 = txtbRealm2AllyVsHorde.Inlines;
                    ilc2.Add(ally2);
                    ilc2.Add(" vs ");
                    ilc2.Add(horde2);
                    break;
                default:
                    //TODO: Błędne ID realmu |w XMl
                    break;
            }

            rs = null;
        }
        private RealmStatus GetRealmStatus(int realmID)
        {
            string id = realmID.ToString();
            XDocument doc = XDocument.Load("http://l5k-programming.pl/Sunwell/RealmStatus.xml");

            var realmStatus =
                from field in doc.Descendants("Realm")
                where (field.Attribute("id").Value == id)
                select new RealmStatus()
                           {
                               name = field.Element("name").Value,
                               type = field.Element("type").Value,
                               status = field.Element("status").Value,
                               uptime = field.Element("uptime").Value,
                               players = field.Element("players").Value,
                               playersMax = field.Element("playersMax").Value,
                               horde = field.Element("horde").Value,
                               alliance = field.Element("alliance").Value,
                               avgDiff = field.Element("avgDiff").Value
                           };

            var name = realmStatus.Select(x => x.name).SingleOrDefault();
            var type = realmStatus.Select(x => x.type).SingleOrDefault();
            var status = realmStatus.Select(x => x.status).SingleOrDefault();
            var uptime = realmStatus.Select(x => x.uptime).SingleOrDefault();
            var players = realmStatus.Select(x => x.players).SingleOrDefault();
            var playersMax = realmStatus.Select(x => x.playersMax).SingleOrDefault();
            var horde = realmStatus.Select(x => x.horde).SingleOrDefault();
            var alliance = realmStatus.Select(x => x.alliance).SingleOrDefault();
            var avgDiff = realmStatus.Select(x => x.avgDiff).SingleOrDefault();

            return new RealmStatus()
                       {
                           name = name,
                           type = type,
                           status = status,
                           uptime = uptime,
                           players = players,
                           playersMax = playersMax,
                           horde = horde,
                           alliance = alliance,
                           avgDiff = avgDiff
                       };
        }
        private BitmapImage GetImgFromUrl(string url)
        {
            var image = new BitmapImage();
            int BytesToRead = 100;

            WebRequest request = WebRequest.Create(new Uri(url, UriKind.Absolute));
            request.Timeout = -1;
            WebResponse response = request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            BinaryReader reader = new BinaryReader(responseStream);
            MemoryStream memoryStream = new MemoryStream();

            byte[] bytebuffer = new byte[BytesToRead];
            int bytesRead = reader.Read(bytebuffer, 0, BytesToRead);

            while (bytesRead > 0)
            {
                memoryStream.Write(bytebuffer, 0, bytesRead);
                bytesRead = reader.Read(bytebuffer, 0, BytesToRead);
            }

            image.BeginInit();
            memoryStream.Seek(0, SeekOrigin.Begin);

            image.StreamSource = memoryStream;
            image.EndInit();

            return image;
        }
        
        private void SerializeXML(Realmlists rls)
        {
            
        }
        private void DeserializeXML(XDocument doc)
        {

        }

        //WATCHER BELOW:
        private void CreateWatcher()
        {
            watcher = new FileSystemWatcher();
            watcher.Filter = "Realmlists.xml";
            watcher.Created += watcher_FileCreated;
            watcher.Path = path; //Base.GetPath();
            watcher.EnableRaisingEvents = true;
        }
        void watcher_FileCreated(object sender, FileSystemEventArgs e)
        {
            doc = LoadXML();
            Dispatcher.Invoke(DispatcherPriority.Normal, new ListItemsAdd(ListItemsAddFromXML), doc);
            //ListItemsAddFromXML(doc);

            watcher.EnableRaisingEvents = false;
            watcher.Created -= watcher_FileCreated;
            watcher.Dispose();
        }

        
        //TEST METHODS BELOW:
        //public void WriteXML()
        //{
        //    Realmlists realmlists = new Realmlists()
        //                              {
        //                                  Realm =
        //                                      new List<Realm>()
        //                                          {
        //                                              new Realm()
        //                                                  {
        //                                                      name = "Sunwell",
        //                                                      address = "176.9.132.194",
        //                                                      website = "http://sunwell.pl/"
        //                                                  },
        //                                                  new Realm()
        //                                                  {
        //                                                      name = "Arena Tournament",
        //                                                      address = "abyssal-wow.com",
        //                                                      website = "http://arena-tournament.com/"
        //                                                  }
        //                                          }
        //                              };

        //    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        //    ns.Add(string.Empty, string.Empty);

        //    XmlSerializer writer = new XmlSerializer(typeof(Realmlists));
        //    StreamWriter file = new StreamWriter(@"c:\temp\SerializationOverview.xml");
        //    writer.Serialize(file, realmlists, ns);
        //    file.Close();
        //}
        public void ReadXML()
        {
            XmlSerializer reader = new XmlSerializer(typeof(Realmlists));
            StreamReader file = new StreamReader(@"c:\temp\SerializationOverview.xml");
            Realmlists realmlists = (Realmlists)reader.Deserialize(file); //new Realmlists();
            //realmlists = (Realmlists)reader.Deserialize(file);

            //Console.WriteLine(realmlists.name);

            var x = realmlists.Realm;
        }
        #endregion
    }
}
